// 移除 <REF> 标签及其内容
export const removeRefTags = (text: string): string => {
  const refTagRegex = new RegExp(`<REF>[\\s\\S]*?</REF>`, 'g');
  return text?.replace(refTagRegex, '');
};

// 检测表格数据并添加默认表头
export const addTableHeader = (text: string): string => {
  const tableRowRegex = /\|[^\n]+\|/g;
  const tableRows = text.match(tableRowRegex);

  if (tableRows && tableRows.length > 1) {
    const secondRow = tableRows[1];
    const hasTableIdentifier = /^\|[^\|]*(:-+:?|:?-+:?)[^\|]*\|/.test(secondRow);
    if (!hasTableIdentifier) {
      const firstRow = tableRows[0];
      const columnCount = (firstRow.match(/\|/g) || []).length - 1; // 计算列数

      // 生成默认表头和分隔行
      const tableHeader = `|${' |'.repeat(columnCount)}`; // 生成表头
      const tableSeparator = `|${'-|'.repeat(columnCount)}`; // 生成分隔行
      const tableRowsString = tableRows.join('\n');
      const tableWithHeader = `${tableHeader}\n${tableSeparator}\n${tableRowsString}`;
      return text?.replace(tableRowsString, tableWithHeader);
    }
  }

  return text;
};

// 处理 URL 后的标点符号
export const fixUrlPunctuation = (text: string): string => {
  const urlWithPunctRegex = new RegExp(
    `(?<!\\]\\()(\\bhttps?:\\/\\/[\\w\\W]+?)([\\u4e00-\\u9fa5，。（）‘’“”'"；、]+)`,
    'g',
  );
  return text?.replace(urlWithPunctRegex, '$1 $2');
};

// 将图片名称转换为 Markdown 图片格式
export const convertImageNames = (text: string): string => {
  const imageNameRegex = new RegExp(`(?<!\!)\\[([\\w\\W]+?\\.(jpg|jpeg|png|gif|bmp|svg))\\]`, 'gi');
  return text?.replace(imageNameRegex, '![$1]');
};

export const preprocessMarkdown = (text: string): string => {
  let processedText = text;
  if (!processedText) return processedText;
  try {
    processedText = removeRefTags(processedText);
    // processedText = addTableHeader(processedText);
    processedText = fixUrlPunctuation(processedText);
    processedText = convertImageNames(processedText);
  } catch (error) {
    console.error('Error during markdown preprocessing:', error);
  }

  return processedText;
};

export const stripIllegalHtmlTags = (input: string): string => {
  // Define the allowed tags
  const allowedTags = [
    'b',
    'table',
    'th',
    'tr',
    'td',
    'thead',
    'tbody',
    'h1',
    'h2',
    'h3',
    'h4',
    'h5',
    'h6',
    'br',
  ];
  // const allowedTags = ['b'];

  // Create a regex pattern to match allowed tags
  const allowedTagsPattern = allowedTags.join('|');

  // Regex to match all HTML tags
  const allTagsRegex = /<\/?([a-z][a-z0-9]*)\b[^>]*>/gi;

  // Replace tags not in the allowed list with an empty string
  return input?.replace(allTagsRegex, (match, tagName) => {
    return allowedTags.includes(tagName.toLowerCase()) ? match : '';
  });
};

/**
 * 正则表达式校验
 * @param text 文本
 * @param pattern 正则表达式
 * @returns 是否匹配
 */
export const regexText = (text: string, pattern: string): boolean => {
  const regex = new RegExp(pattern);
  return regex.test(text);
};
